'use client';

import { ChatModel } from '@/db/schema';
import { useUser } from '@clerk/nextjs';
import { useQuery } from '@tanstack/react-query';
import axios from 'axios';
import { usePathname, useRouter } from 'next/navigation';
import React from 'react'
import AddCircleOutlineIcon from '@mui/icons-material/AddCircleOutline';

const Navbar = () => {

  const { user } = useUser()
  const router = useRouter()
  const { data: chats } = useQuery({
    queryKey: ['chats'],
    queryFn: async () => {
      return axios.post('/api/get-chats')
    },
    enabled: !!user?.id
  })

  const pathName = usePathname()

  return (
    <div className='h-screen bg-gray-50/90 border-r border-gray-200/70 backdrop-blur-sm'>
      <div className='flex items-center justify-center py-5'>
        <p className='font-bold text-2xl text-blue-600/90'>
          Kurumi AI
        </p>
      </div>

      <div className='h-10 flex items-center justify-center mt-2 mb-4 px-4'
        onClick={() => router.push('/')}
      >
        <div className='h-full w-full bg-blue-500/90 hover:bg-blue-600/90 rounded-lg flex items-center justify-center transition-all duration-200 cursor-pointer shadow-sm backdrop-blur-sm'>
          <AddCircleOutlineIcon className="text-white/95 mr-2" fontSize="small" />
          <p className='text-white/95 font-medium'>
            创建新会话
          </p>
        </div>
      </div>

      <div className='flex flex-col items-start justify-start gap-1 px-4 mt-6 max-h-[70vh] overflow-y-auto scrollbar-hide'>
        <p className='text-xs text-gray-500/90 font-medium ml-2 mb-2'>历史会话</p>
        {chats?.data?.map((chat: ChatModel) => (
          <div
            className={`w-full py-2 px-3 rounded-md cursor-pointer transition-all duration-200 ${pathName === `/chat/${chat.id}`
              ? 'bg-blue-50/90 text-blue-600/90 border-l-2 border-blue-500/80 shadow-sm'
              : 'hover:bg-gray-100/80'
              }`}
            key={chat.id}
            onClick={() => router.push(`/chat/${chat.id}`)}
          >
            <p className={`font-medium text-sm line-clamp-1 ${pathName === `/chat/${chat.id}`
              ? 'text-blue-600/90'
              : 'text-gray-700/90'
              }`}>
              {chat.title}
            </p>
          </div>
        ))}
      </div>
    </div>
  )
}

export default Navbar